﻿using System.CodeDom;
using System.Reflection;
using SmartStringResources.CodeDom;

namespace SmartStringResources
{
    internal class ResourceKeysBuilder
    {
        private readonly ResourceArea _area;

        public ResourceKeysBuilder(ResourceArea area)
        {
            _area = area;
        }

        public CodeTypeDeclaration Build(string targetClassName, AccessibilityLevel accessibilityLevel)
        {
            var codeClass = new CodeTypeDeclaration(targetClassName ?? _area.ValidIdentifierName)
            {
                IsClass = true,
                TypeAttributes = accessibilityLevel.GetTypeAttribute() | TypeAttributes.Class,
            };
            codeClass.Comments.AddSummaryComments(Strings.GeneratorResources.ResourcesKeysClassComments());
            codeClass.AddDefaultAttributes();

            foreach (var resourceValue in _area.Values)
            {
                var resourceKey = string.Concat(_area.Prefix, resourceValue.Name);

                var member = new CodeMemberField
                {
                    Name = resourceValue.ValidIdentifierName,
                    Attributes = MemberAttributes.Public | MemberAttributes.Const,
                    Type = new CodeTypeReference(typeof(string)),
                    InitExpression = new CodePrimitiveExpression(resourceKey)
                };

                member.Comments.AddSummaryComments(Strings.GeneratorResources.ResourcesKeysMemberComments(resourceValue: resourceValue.Value));

                codeClass.Members.Add(member);
            }

            foreach (var nestedArea in _area.NestedAreas)
            {
                var resourceKeysBuilder = new ResourceKeysBuilder(nestedArea);
                codeClass.Members.Add(resourceKeysBuilder.Build(null, accessibilityLevel));
            }

            return codeClass;
        }
    }
}